import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author ml
 * @create 2018-02-07--10:23
 */
@WebServlet("/uploadservlet")
@MultipartConfig
public class UploadServlet extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Part part=req.getPart("file");

            String name=part.getHeader("content-disposition");

//        获取上传文件路径
            String root=req.getServletContext().getRealPath("/upload");
            File rootdic=new File(root);
            if(!rootdic.exists()){
                rootdic.mkdirs();
            }
            System.out.println("root = " + root);

//        获取文件的后缀

            String suffix=name.substring(name.lastIndexOf("."),name.length()-1);
            System.out.println("suffix = " + suffix);

            String filename=root+"\\"+ UUID.randomUUID().toString()+suffix;
            System.out.println("filename = " + filename);

            File myfile=new File(filename);
            if(!myfile.exists()){
                myfile.createNewFile();
            }


            part.write(filename);
            req.setAttribute("info","上传文件成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
